package org.example.projectdemo.controller;

import jakarta.validation.Valid;
import org.example.projectdemo.advice.ErrorResponse;
import org.example.projectdemo.model.entity.User;
import org.example.projectdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 认证控制器
 * 处理用户认证相关的HTTP请求，如登录和登出
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;

    /**
     * 用户登录认证
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");

        if (username == null || password == null) {
            ErrorResponse errorResponse = new ErrorResponse("INVALID_CREDENTIALS", "用户名和密码不能为空");
            return ResponseEntity.badRequest().body(errorResponse);
        }

        Optional<User> userOptional = userService.getUserByUsername(username);

        if (userOptional.isPresent() && userOptional.get().getPassword().equals(password)) {
            User user = userOptional.get();
            // 返回不包含密码的用户信息
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("token", "mock-token-" + user.getId()); // 模拟token，实际项目中应该使用JWT
            response.put("user", Map.of(
                    "id", user.getId(),
                    "username", user.getUsername()
                    // 不返回密码字段
            ));
            return ResponseEntity.ok(response);
        } else {
            ErrorResponse errorResponse = new ErrorResponse("LOGIN_FAILED", "用户名或密码错误");
            return ResponseEntity.status(401).body(errorResponse);
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "登出成功");
        return ResponseEntity.ok(response);
    }
}